<template>
  <div class="new-products-page">
    <header-nav />
    
    <!-- Banner区域 -->
    <div class="banner">
      <h1>新增毛绒玩具</h1>
      <p>我们所有的新 StoryPlush 朋友都集中在一个地方!</p>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 左侧筛选器 -->
      <div class="filter-sidebar">
        <div class="filter-header">
          <el-icon><Filter /></el-icon>
          <span>筛选器</span>
        </div>
        
        <el-divider />
        
        <div class="filter-section">
          <h3>价格区间</h3>
          <el-form :model="filterForm">
            <el-form-item>
              <el-slider
                v-model="filterForm.priceRange"
                range
                :min="0"
                :max="1000"
                :marks="{
                  0: '¥0',
                  250: '¥250',
                  500: '¥500',
                  750: '¥750',
                  1000: '¥1000'
                }"
                @change="handlePriceChange"
              />
            </el-form-item>
          </el-form>
        </div>
        
        <el-divider />
        
        <div class="filter-section">
          <h3>分类</h3>
          <el-checkbox-group v-model="filterForm.categories">
            <el-checkbox label="stuffed">毛绒玩具</el-checkbox>
            <el-checkbox label="animals">动物系列</el-checkbox>
            <el-checkbox label="dolls">玩偶系列</el-checkbox>
            <el-checkbox label="accessories">配件</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <!-- 右侧商品展示 -->
      <div class="products-container">
        <!-- 排序和统计 -->
        <div class="products-header">
          <div class="products-count">
            {{ total }} 个商品
          </div>
          <div class="sort-options">
            <el-radio-group v-model="filterForm.sort" size="small">
              <el-radio-button label="newest">最新上架</el-radio-button>
              <el-radio-button label="price_asc">价格从低到高</el-radio-button>
              <el-radio-button label="price_desc">价格从高到低</el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <!-- 商品列表 -->
        <div v-if="loading" class="loading">
          <el-skeleton :count="8" animated>
            <template #template>
              <el-card class="product-skeleton">
                <template #default>
                  <el-skeleton-item variant="image" style="width: 100%; height: 200px" />
                  <div style="padding: 14px">
                    <el-skeleton-item variant="h3" style="width: 50%" />
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 8px">
                      <el-skeleton-item variant="text" style="width: 30%" />
                      <el-skeleton-item variant="text" style="width: 20%" />
                    </div>
                  </div>
                </template>
              </el-card>
            </template>
          </el-skeleton>
        </div>
        <div v-else class="products-grid">
          <el-card 
            v-for="product in products" 
            :key="product.id" 
            class="product-card"
            :body-style="{ padding: '0px' }"
            shadow="hover"
          >
            <div class="product-image">
              <el-image 
                :src="getImageUrl(product.image)"
                fit="cover"
                loading="lazy"
                :preview-src-list="[getImageUrl(product.image)]"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <p>图片加载失败</p>
                  </div>
                </template>
                <template #placeholder>
                  <div class="image-loading">
                    <el-icon><Loading /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="new-tag">新品</div>
            </div>
            <div class="product-info">
              <h3>{{ product.name }}</h3>
              <p class="description">{{ product.description }}</p>
              <div class="product-price">
                <span class="price">
                  <small>¥</small>{{ formatPrice(product.price) }}
                </span>
                <el-button 
                  type="primary" 
                  size="small" 
                  circle
                  @click="handleAddToCart(product)"
                >
                  <el-icon><Plus /></el-icon>
                </el-button>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[12, 24, 36]"
            layout="total, sizes, prev, pager, next"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import HeaderNav from '../components/HeaderNav.vue'
import { ElMessage } from 'element-plus'
import { Filter, Picture, Plus, Loading } from '@element-plus/icons-vue'
import axios from '../utils/axios'

const loading = ref(false)
const products = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)

const filterForm = ref({
  sort: 'newest',
  priceRange: [0, 1000],
  categories: []
})

const handlePriceChange = (val) => {
  filterForm.value.minPrice = val[0]
  filterForm.value.maxPrice = val[1]
}

const handleAddToCart = async (product) => {
  try {
    await axios.post('/api/cart', {
      productId: product.id,
      quantity: 1
    })
    ElMessage.success('已添加到购物车')
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('添加失败')
  }
}

const fetchProducts = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      sort: filterForm.value.sort,
      minPrice: filterForm.value.priceRange[0],
      maxPrice: filterForm.value.priceRange[1]
    };

    // 只有当有选中的分类时才添加 categories 参数
    if (filterForm.value.categories.length > 0) {
      params.categories = filterForm.value.categories.join(',');
    }

    console.log('Fetching products with params:', params);

    const { data } = await axios.get('/api/products/new', { params });

    console.log('Received products:', data);
    products.value = data.products;
    total.value = data.total;
  } catch (error) {
    console.error('Error fetching products:', error);
    ElMessage.error('获取商品列表失败');
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchProducts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProducts()
}

watch(filterForm, () => {
  currentPage.value = 1
  fetchProducts()
}, { deep: true })

onMounted(() => {
  fetchProducts()
})

// 格式化价格
const formatPrice = (price) => {
  return typeof price === 'number' ? price.toFixed(2) : '0.00'
}

// 处理图片URL
const getImageUrl = (path) => {
  if (path.startsWith('http')) {
    return path;
  }
  // 确保路径正确拼接
  const baseUrl = import.meta.env.VITE_API_URL;
  return `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;
}

</script>

<style scoped>
.new-products-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.banner {
  height: 200px;
  background: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.3)), url('/images/new-bg.png');
  background-size: cover;
  background-position: center;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  margin-top: 60px;
}

.banner h1 {
  font-size: 36px;
  margin-bottom: 10px;
}

.banner p {
  font-size: 18px;
  opacity: 0.9;
}

.main-content {
  max-width: 1400px;
  margin: 30px auto;
  padding: 0 40px;
  display: flex;
  gap: 40px;
}

.filter-sidebar {
  width: 300px;
  background: white;
  padding: 25px;
  border-radius: 12px;
  position: sticky;
  top: 80px;
  height: fit-content;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.filter-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: bold;
}

.filter-section {
  margin: 25px 0;
}

.filter-section h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

.products-container {
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
}

.products-header {
  background: white;
  padding: 20px 25px;
  border-radius: 12px;
  margin-bottom: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.products-count {
  font-size: 16px;
  color: #666;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
}

.product-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.product-image {
  position: relative;
  height: 280px;
  overflow: hidden;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
}

.new-tag {
  position: absolute;
  top: 15px;
  right: 15px;
  background: #ff6b6b;
  color: white;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}

.product-info {
  padding: 20px;
}

.product-info h3 {
  font-size: 18px;
  margin-bottom: 10px;
}

.description {
  font-size: 14px;
  line-height: 1.5;
  height: 42px;
  margin: 10px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制为2行 */
}

.product-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.price {
  font-size: 24px;
  color: #ff6b6b;
  font-weight: 600;
}

.price small {
  font-size: 16px;
  margin-right: 4px;
}

.image-error {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
  color: #999;
}

.image-error p {
  margin-top: 8px;
  font-size: 14px;
}

.image-loading {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
}

.image-loading .el-icon {
  font-size: 24px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.pagination {
  margin: 40px 0;
}

/* 使用深度选择器修复分页样式 */
.pagination :deep(.el-pagination) {
  justify-content: center;
}

.pagination :deep(.el-pagination__total) {
  margin-right: 20px;
}

.pagination :deep(.el-pagination__sizes) {
  margin-right: 20px;
}

/* 响应式布局 */
@media (min-width: 1600px) {
  .main-content {
    max-width: 1600px;
  }

  .products-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 1400px) {
  .products-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 1200px) {
  .main-content {
    padding: 0 20px;
  }

  .products-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
    padding: 0 15px;
  }
  
  .filter-sidebar {
    width: 100%;
    position: static;
    margin-bottom: 20px;
  }
  
  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }

  .product-image {
    height: 200px;
  }

  .product-info {
    padding: 15px;
  }

  .product-info h3 {
    font-size: 16px;
  }
}

/* 修复排序按钮组样式 */
.sort-options :deep(.el-radio-button__inner) {
  padding: 8px 20px;
}
</style> 